import urllib
from trytond.model import ModelView, ModelSQL, fields
from trytond.transaction import Transaction


class Address(ModelSQL, ModelView):
    _name = 'party.address'

    openstreetmap_url = fields.Function(fields.Char('OpenStreetMap',
        on_change_with=['country', 'subdivision', 'city', 'street']), 'get_openstreetmap_url')

    def _get_url(self, vals):
        lang = Transaction().language[:2]
        url = ''
        for i in ['country', 'subdivision', 'city', 'street']:
            if vals.get(i):
                if isinstance(vals[i], str):
                    url += '/' + vals[i].decode('utf-8')
                else:
                    url += '/' + vals[i]
        if url.strip():
            url = 'http://nominatim.openstreetmap.org/search/%s' % urllib.quote(url.strip().encode('utf-8')))
        else:
            url = ''
        return url

    def on_change_with_openstreetmap_url(self, vals):
        country_obj = self.pool.get('country.country')
        subdivision_obj = self.pool.get('country.subdivision')

        vals = vals.copy()

        if vals.get('country'):
            country = country_obj.browse(vals['country'])
            vals['country'] = country.name

        if vals.get('subdivision'):
            subdivision = subdivision_obj.browse(vals['subdivision'])
            vals['subdivision'] = subdivision.name

        return self._get_url(vals)

    def get_openstreetmap_url(self, ids, name):
        res = {}
        for address in self.browse(ids):
            vals = {
                'street': address.street,
                'city': address.city,
                'country': address.country and address.country.name or False,
                'subdivision': address.subdivision and \
                        address.subdivision.name or False,
            }
            res[address.id] = self._get_url(vals)
        return res

Address()
